package multimedia;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.rmi.RemoteException;

import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;

import ui.VadeMecumImageViewer;
import util.Base64Encoder;
import webservice.VadeMecumMultimediaServicePortType_Stub;

import midlet.VadeMecumMIDlet;

public class SendToServiceWithoutContextThread implements Runnable {

	private VadeMecumMIDlet midlet;
	
	private byte[] imageArray;
	
	private Alert alert;
	
	private VadeMecumImageViewer previous;
	
	public SendToServiceWithoutContextThread(VadeMecumMIDlet midlet, VadeMecumImageViewer previous, byte[] imageArray) {
		this.midlet = midlet;
		this.imageArray = imageArray;
		this.previous = previous;
		alert = new Alert("", "Picture sent to server!", null, AlertType.INFO);
		alert.setTimeout(1500);
	}
	
	public void run() {
		System.out.println("vai mandar sem contexto");
		VadeMecumMultimediaServicePortType_Stub stub = new VadeMecumMultimediaServicePortType_Stub();
		try {
			String pictureEncoded = Base64Encoder.base64Encode(imageArray);			
			long fileId = System.currentTimeMillis();			
			stub.saveWithoutContext("vm_picture" + fileId + ".jpg", pictureEncoded);
			previous.repaint();
			midlet.display.setCurrent(alert, previous);
		} catch (RemoteException re) {
			if ("SAXParseException in response from server".equals(re.getMessage().trim())){
				previous.repaint();
				midlet.display.setCurrent(alert, previous);
			} else {				
				midlet.error(re);
			}
		}
	}

}
